package com.coltsmedia.RichmondHighNews;

import android.content.Context;
import android.content.Intent;
import android.content.res.Configuration;
import android.net.Uri;
import android.os.Bundle;
import android.support.v4.app.ActionBarDrawerToggle;
import android.support.v4.widget.DrawerLayout;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.TextView;

import com.actionbarsherlock.app.ActionBar;
import com.actionbarsherlock.app.SherlockFragmentActivity;
import com.coltsmedia.RichmondHighNews.adapter.ArticleListAdapter;
import com.coltsmedia.RichmondHighNews.db.DbAdapter;
import com.coltsmedia.RichmondHighNews.rss.domain.Article;


public class ArticleListActivity extends SherlockFragmentActivity implements ArticleListFragment.Callbacks {


    private boolean mTwoPane;
    private DbAdapter dba;

    private DrawerLayout mDrawerLayout;
    private ListView mDrawerList;
    private ActionBarDrawerToggle mDrawerToggle;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_article_list);

        dba = new DbAdapter(this);
        mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout1);
        mDrawerList = (ListView) findViewById(R.id.left_drawer_list);

        mDrawerToggle = new ActionBarDrawerToggle(this, mDrawerLayout,
                R.drawable.ic_drawer, //nav menu toggle icon
                R.string.news_feed, // nav drawer open - description for accessibility
                R.string.news_feed // nav drawer close - description for accessibility
        ) {
            public void onDrawerClosed(View view) {
                super.onDrawerClosed(view);
                getActionBar().setTitle(R.string.news_feed);
                // calling onPrepareOptionsMenu() to show action bar icons
            }
            public void onDrawerOpened(View drawerView) {
                super.onDrawerOpened(drawerView);
                getActionBar().setTitle("Menu");
            }
        };
        mDrawerLayout.setDrawerListener(mDrawerToggle);

        ActionBar ab = getSupportActionBar();
        ab.setHomeButtonEnabled(true);
        ab.setDisplayHomeAsUpEnabled(true);
        populateListView();

        if (findViewById(R.id.article_detail_container) != null) {
            mTwoPane = true;
            ((ArticleListFragment) getSupportFragmentManager()
                    .findFragmentById(R.id.article_list))
                    .setActivateOnItemClick(true);
        }
    }

    public static Intent getOpenFacebookIntent(Context context) {

        try {
            context.getPackageManager().getPackageInfo("com.facebook.katana", 0);                       //Checks if FB is even installed.
            return new Intent(Intent.ACTION_VIEW, Uri.parse("fb://page/391234834280206"));              //Tries to make intent with Facebook's URI
        } catch (Exception e) {
            return new Intent(Intent.ACTION_VIEW, Uri.parse("https://www.facebook.com/RichmondColts")); //Catches and opens a url to the desired page
        }
    }

    private void populateListView() {

        String[] options = getResources().getStringArray(R.array.tut_titles);
        final ArrayAdapter<String> arrayAdapter = new ArrayAdapter<String>(this, R.layout.menu_list, options);
        final ListView list = (ListView) findViewById(R.id.left_drawer_list);
        list.setAdapter(arrayAdapter);

        list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                // When clicked, show a toast with the TextView text
                //Toast.makeText(getApplicationContext() ,((TextView) view).getText() , Toast.LENGTH_SHORT).show();

                String url1 = "http://rhs.sd38.bc.ca/";
                String url2 = "https://twitter.com/RichmondColts";
                TextView text1 = (TextView) view.findViewById(R.id.menu_view);

                if (text1.getText().toString().equals("Richmond High School")) {
                    final Intent intent1 = new Intent(Intent.ACTION_VIEW, Uri.parse(url1));
                    startActivity(intent1);
                }
                else if (text1.getText().toString().equals("Richmond High Twitter")) {
                   final Intent intent2 = new Intent(Intent.ACTION_VIEW, Uri.parse(url2));
                   startActivity(intent2);
                }
                else if (text1.getText().toString().equals("Richmond High Facebook")) {
                    final Intent intent3 = getOpenFacebookIntent(ArticleListActivity.this);
                    startActivity(intent3);
                }
                else if (text1.getText().toString().equals("Main Menu")){
                    final Intent intent5 = new Intent(ArticleListActivity.this, MainMenuActivity.class);
                    intent5.addFlags(Intent.FLAG_ACTIVITY_NO_ANIMATION);
                    startActivity(intent5);
                    overridePendingTransition(0,0);
                }
            }

        });
    }

	@Override
    public void onItemSelected(String id) {
        Article selected = (Article) ((ArticleListFragment) getSupportFragmentManager().findFragmentById(R.id.article_list)).getListAdapter().getItem(Integer.parseInt(id));

        //mark article as read
        dba.openToWrite();
        dba.markAsRead(selected.getGuid());
        dba.close();
        selected.setRead(true);
        ArticleListAdapter adapter = (ArticleListAdapter) ((ArticleListFragment) getSupportFragmentManager().findFragmentById(R.id.article_list)).getListAdapter();
        adapter.notifyDataSetChanged();
        Log.e("CHANGE", "Changing to read: ");

        //load article details to main panel
        final Bundle arguments = new Bundle();
        arguments.putSerializable (Article.KEY, selected);
        if (mTwoPane) {

            ArticleDetailFragment fragment = new ArticleDetailFragment();
            fragment.setArguments(arguments);
            getSupportFragmentManager().beginTransaction()
                    .replace(R.id.article_detail_container, fragment)
                    .commit();

        } else {
            Intent detailIntent = new Intent(this, ArticleDetailActivity.class);
            detailIntent.putExtra("arguments", arguments);
            startActivity(detailIntent);
        }
    }

    @Override
    protected void onPause(){
        super.onPause();
        overridePendingTransition(0,0);
    }

    @Override
    protected void onPostCreate(Bundle savedInstanceState) {
        super.onPostCreate(savedInstanceState);
        // Sync the toggle state after onRestoreInstanceState has occurred.
        mDrawerToggle.syncState();
    }

    @Override
    public void onConfigurationChanged(Configuration newConfig) {
        super.onConfigurationChanged(newConfig);
        mDrawerToggle.onConfigurationChanged(newConfig);
    }

    @Override
    public boolean onOptionsItemSelected(com.actionbarsherlock.view.MenuItem item) {
        switch (item.getItemId()) {
            case android.R.id.home:
                if (mDrawerLayout.isDrawerOpen(mDrawerList)) {
                    mDrawerLayout.closeDrawer(mDrawerList);
                } else {
                    mDrawerLayout.openDrawer(mDrawerList);
                }
                return true;
            case R.id.actionbar_refresh:
                return false;
            default:
                break;
        }
        return false;
    }
}
